<template>
  <div class="app-container">
    <el-form :model="queryParams" ref="queryRef" :inline="true" v-show="showSearch" label-width="68px">
      <el-form-item label="策略名称" prop="strategyName">
        <el-input
          v-model="queryParams.strategyName"
          placeholder="请输入策略名称"
          clearable
          @keyup.enter="handleQuery"
        />
      </el-form-item>
      <el-form-item label="折扣类型" prop="discountType">
        <el-select v-model="queryParams.discountType" placeholder="请选择折扣类型" clearable>
          <el-option
            v-for="dict in discount_type"
            :key="dict.value"
            :label="dict.label"
            :value="dict.value"
          />
        </el-select>
      </el-form-item>
      <el-form-item label="状态" prop="status">
        <el-select v-model="queryParams.status" placeholder="请选择状态" clearable>
          <el-option label="启用" value="1" />
          <el-option label="禁用" value="0" />
        </el-select>
      </el-form-item>
      <el-form-item label="创建时间">
        <el-date-picker
          v-model="dateRange"
          value-format="YYYY-MM-DD"
          type="daterange"
          range-separator="-"
          start-placeholder="开始日期"
          end-placeholder="结束日期"
        ></el-date-picker>
      </el-form-item>
      <el-form-item>
        <el-button type="primary" icon="Search" @click="handleQuery">搜索</el-button>
        <el-button icon="Refresh" @click="resetQuery">重置</el-button>
      </el-form-item>
    </el-form>

    <el-row :gutter="10" class="mb8">
      <el-col :span="1.5">
        <el-button
          type="primary"
          plain
          icon="Plus"
          @click="handleAdd"
          v-hasPermi="['manage:strategy:add']"
        >新增</el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button
          type="success"
          plain
          icon="Edit"
          :disabled="single"
          @click="handleUpdate"
          v-hasPermi="['manage:strategy:edit']"
        >修改</el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button
          type="danger"
          plain
          icon="Delete"
          :disabled="multiple"
          @click="handleDelete"
          v-hasPermi="['manage:strategy:remove']"
        >删除</el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button
          type="warning"
          plain
          icon="Download"
          @click="handleExport"
          v-hasPermi="['manage:strategy:export']"
        >导出</el-button>
      </el-col>
      <right-toolbar v-model:showSearch="showSearch" @queryTable="getList"></right-toolbar>
    </el-row>

    <el-table v-loading="loading" :data="strategyList" @selection-change="handleSelectionChange">
      <el-table-column type="selection" width="55" align="center" />
      <el-table-column label="策略ID" align="center" prop="id" />
      <el-table-column label="策略名称" align="center" prop="strategyName" />
      <el-table-column label="策略描述" align="center" prop="strategyDesc" show-overflow-tooltip />
      <el-table-column label="折扣类型" align="center" prop="discountType">
        <template #default="scope">
          <dict-tag :options="discount_type" :value="scope.row.discountType"/>
        </template>
      </el-table-column>
      <el-table-column label="折扣值" align="center" prop="discountValue">
        <template #default="scope">
          <span v-if="scope.row.discountType == 1">{{ scope.row.discountValue }}折</span>
          <span v-else>减{{ scope.row.discountValue }}元</span>
        </template>
      </el-table-column>
      <el-table-column label="最低消费" align="center" prop="minAmount">
        <template #default="scope">
          {{ scope.row.minAmount }}元
        </template>
      </el-table-column>
      <el-table-column label="开始时间" align="center" prop="startTime" width="180">
        <template #default="scope">
          <span>{{ parseTime(scope.row.startTime, '{y}-{m}-{d} {h}:{i}:{s}') }}</span>
        </template>
      </el-table-column>
      <el-table-column label="结束时间" align="center" prop="endTime" width="180">
        <template #default="scope">
          <span>{{ parseTime(scope.row.endTime, '{y}-{m}-{d} {h}:{i}:{s}') }}</span>
        </template>
      </el-table-column>
      <el-table-column label="状态" align="center" prop="status">
        <template #default="scope">
          <el-tag :type="scope.row.status == 1 ? 'success' : 'danger'">
            {{ scope.row.status == 1 ? '启用' : '禁用' }}
          </el-tag>
        </template>
      </el-table-column>
      <el-table-column label="操作" align="center" class-name="small-padding fixed-width">
        <template #default="scope">
          <el-button
            type="text"
            icon="View"
            @click="handleDeviceAssign(scope.row)"
            v-hasPermi="['manage:strategy:assign']"
          >分配设备</el-button>
          <el-button
            type="text"
            icon="Edit"
            @click="handleUpdate(scope.row)"
            v-hasPermi="['manage:strategy:edit']"
          >修改</el-button>
          <el-button
            type="text"
            icon="Delete"
            @click="handleDelete(scope.row)"
            v-hasPermi="['manage:strategy:remove']"
          >删除</el-button>
        </template>
      </el-table-column>
    </el-table>

    <pagination
      v-show="total>0"
      :total="total"
      v-model:page="queryParams.pageNum"
      v-model:limit="queryParams.pageSize"
      @pagination="getList"
    />

    <!-- 添加或修改折扣策略对话框 -->
    <el-dialog :title="title" v-model="open" width="500px" append-to-body>
      <el-form ref="strategyRef" :model="form" :rules="rules" label-width="80px">
        <el-form-item label="策略名称" prop="strategyName">
          <el-input v-model="form.strategyName" placeholder="请输入策略名称" />
        </el-form-item>
        <el-form-item label="策略描述" prop="strategyDesc">
          <el-input v-model="form.strategyDesc" type="textarea" placeholder="请输入策略描述" />
        </el-form-item>
        <el-form-item label="折扣类型" prop="discountType">
          <el-select v-model="form.discountType" placeholder="请选择折扣类型">
            <el-option
              v-for="dict in discount_type"
              :key="dict.value"
              :label="dict.label"
              :value="parseInt(dict.value)"
            ></el-option>
          </el-select>
        </el-form-item>
        <el-form-item label="折扣值" prop="discountValue">
          <el-input-number
            v-model="form.discountValue"
            :min="0.01"
            :max="form.discountType == 1 ? 9.99 : 999.99"
            :precision="form.discountType == 1 ? 2 : 2"
            :step="form.discountType == 1 ? 0.1 : 1"
          />
          <span class="ml-2" v-if="form.discountType == 1">折 (如: 8.0表示8折)</span>
          <span class="ml-2" v-else>元 (固定减免金额)</span>
        </el-form-item>
        <el-form-item label="最低消费" prop="minAmount">
          <el-input-number v-model="form.minAmount" :min="0" :precision="2" />
          <span class="ml-2">元</span>
        </el-form-item>
        <el-form-item label="最大折扣" prop="maxDiscount" v-if="form.discountType == 1">
          <el-input-number v-model="form.maxDiscount" :min="0" :precision="2" />
          <span class="ml-2">元 (可选)</span>
        </el-form-item>
        <el-form-item label="开始时间" prop="startTime">
          <el-date-picker
            v-model="form.startTime"
            type="datetime"
            placeholder="选择开始时间"
            value-format="YYYY-MM-DD HH:mm:ss"
          />
        </el-form-item>
        <el-form-item label="结束时间" prop="endTime">
          <el-date-picker
            v-model="form.endTime"
            type="datetime"
            placeholder="选择结束时间"
            value-format="YYYY-MM-DD HH:mm:ss"
          />
        </el-form-item>
        <el-form-item label="状态" prop="status">
          <el-radio-group v-model="form.status">
            <el-radio :label="1">启用</el-radio>
            <el-radio :label="0">禁用</el-radio>
          </el-radio-group>
        </el-form-item>
        <el-form-item label="备注" prop="remark">
          <el-input v-model="form.remark" type="textarea" placeholder="请输入内容" />
        </el-form-item>
      </el-form>
      <template #footer>
        <div class="dialog-footer">
          <el-button type="primary" @click="submitForm">确 定</el-button>
          <el-button @click="cancel">取 消</el-button>
        </div>
      </template>
    </el-dialog>

    <!-- 设备分配对话框 -->
    <el-dialog title="策略设备分配" v-model="assignOpen" width="800px" append-to-body>
      <el-form :model="assignForm" label-width="100px">
        <el-form-item label="策略名称">
          <el-tag>{{ currentStrategy.strategyName }}</el-tag>
        </el-form-item>
        <el-form-item label="分配设备">
          <el-transfer
            v-model="assignForm.deviceIds"
            :data="deviceList"
            :titles="['可选设备', '已选设备']"
            :props="{ key: 'id', label: 'label' }"
            filterable
            :filter-placeholder="'搜索设备'"
          />
        </el-form-item>
      </el-form>
      <template #footer>
        <div class="dialog-footer">
          <el-button type="primary" @click="submitAssign">确 定</el-button>
          <el-button @click="assignOpen = false">取 消</el-button>
        </div>
      </template>
    </el-dialog>
  </div>
</template>

<script setup name="Strategy">
import { listStrategy, getStrategy, delStrategy, addStrategy, updateStrategy, assignDevicesToStrategy, unassignDevicesFromStrategy } from "@/api/manage/strategy";
import { listVendingMachine } from "@/api/manage/vendingMachine";

const { proxy } = getCurrentInstance();
const { discount_type } = proxy.useDict('discount_type');

const strategyList = ref([]);
const open = ref(false);
const assignOpen = ref(false);
const loading = ref(true);
const showSearch = ref(true);
const ids = ref([]);
const single = ref(true);
const multiple = ref(true);
const total = ref(0);
const title = ref("");
const dateRange = ref([]);

const currentStrategy = ref({});
const deviceList = ref([]);

const data = reactive({
  form: {},
  queryParams: {
    pageNum: 1,
    pageSize: 10,
    strategyName: null,
    discountType: null,
    status: null,
  },
  assignForm: {
    strategyId: null,
    deviceIds: []
  },
  rules: {
    strategyName: [
      { required: true, message: "策略名称不能为空", trigger: "blur" }
    ],
    discountType: [
      { required: true, message: "折扣类型不能为空", trigger: "change" }
    ],
    discountValue: [
      { required: true, message: "折扣值不能为空", trigger: "blur" }
    ],
    startTime: [
      { required: true, message: "开始时间不能为空", trigger: "change" }
    ],
    endTime: [
      { required: true, message: "结束时间不能为空", trigger: "change" }
    ],
    status: [
      { required: true, message: "状态不能为空", trigger: "change" }
    ]
  }
});

const { queryParams, form, assignForm, rules } = toRefs(data);

/** 查询折扣策略列表 */
function getList() {
  loading.value = true;
  queryParams.value.params = {};
  if (null != dateRange.value && '' != dateRange.value) {
    queryParams.value.params["beginTime"] = dateRange.value[0];
    queryParams.value.params["endTime"] = dateRange.value[1];
  }
  listStrategy(queryParams.value).then(response => {
    strategyList.value = response.rows;
    total.value = response.total;
    loading.value = false;
  });
}

// 取消按钮
function cancel() {
  open.value = false;
  reset();
}

// 表单重置
function reset() {
  form.value = {
    id: null,
    strategyName: null,
    strategyDesc: null,
    discountType: null,
    discountValue: null,
    minAmount: 0,
    maxDiscount: null,
    startTime: null,
    endTime: null,
    status: 1,
    remark: null
  };
  proxy.resetForm("strategyRef");
}

/** 搜索按钮操作 */
function handleQuery() {
  queryParams.value.pageNum = 1;
  getList();
}

/** 重置按钮操作 */
function resetQuery() {
  dateRange.value = [];
  proxy.resetForm("queryRef");
  handleQuery();
}

// 多选框选中数据
function handleSelectionChange(selection) {
  ids.value = selection.map(item => item.id);
  single.value = selection.length !== 1;
  multiple.value = !selection.length;
}

/** 新增按钮操作 */
function handleAdd() {
  reset();
  open.value = true;
  title.value = "添加折扣策略";
}

/** 修改按钮操作 */
function handleUpdate(row) {
  reset();
  const _id = row.id || ids.value;
  getStrategy(_id).then(response => {
    form.value = response.data;
    open.value = true;
    title.value = "修改折扣策略";
  });
}

/** 提交按钮 */
function submitForm() {
  proxy.$refs["strategyRef"].validate(valid => {
    if (valid) {
      if (form.value.id != null) {
        updateStrategy(form.value).then(response => {
          proxy.$modal.msgSuccess("修改成功");
          open.value = false;
          getList();
        });
      } else {
        addStrategy(form.value).then(response => {
          proxy.$modal.msgSuccess("新增成功");
          open.value = false;
          getList();
        });
      }
    }
  });
}

/** 删除按钮操作 */
function handleDelete(row) {
  const _ids = row.id || ids.value;
  proxy.$modal.confirm('是否确认删除折扣策略编号为"' + _ids + '"的数据项？').then(function() {
    return delStrategy(_ids);
  }).then(() => {
    getList();
    proxy.$modal.msgSuccess("删除成功");
  }).catch(() => {});
}

/** 导出按钮操作 */
function handleExport() {
  proxy.download('manage/strategy/export', {
    ...queryParams.value
  }, `strategy_${new Date().getTime()}.xlsx`)
}

/** 设备分配按钮操作 */
function handleDeviceAssign(row) {
  currentStrategy.value = row;
  assignForm.value.strategyId = row.id;
  assignForm.value.deviceIds = [];

  // 获取设备列表
  listVendingMachine({}).then(response => {
    deviceList.value = response.rows.map(item => ({
      id: item.id,
      label: `${item.innerCode} - ${item.addr}`
    }));
  });

  assignOpen.value = true;
}

/** 提交设备分配 */
function submitAssign() {
  assignDevicesToStrategy(assignForm.value).then(response => {
    proxy.$modal.msgSuccess("分配成功");
    assignOpen.value = false;
    getList();
  });
}

getList();
</script>